#!/usr/bin/python

"""Project Euler Solution 026

Copyright (c) 2011 by Robert Vella - robert.r.h.vella@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import cProfile
from euler.list_functions import first, max_by

def get_answer():
    """Question:
    
    A unit fraction contains 1 in the numerator. The decimal 
    representation of the unit fractions with denominators 2 to 10 are 
    given:

    1/2    =     0.5
    1/3    =     0.(3)
    1/4    =     0.25
    1/5    =     0.2
    1/6    =     0.1(6)
    1/7    =     0.(142857)
    1/8    =     0.125
    1/9    =     0.(1)
    1/10    =     0.1

    Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. 
    It can be seen that 1/7 has a 6-digit recurring cycle.

    Find the value of d < 1000 for which 1/d contains the longest 
    recurring cycle in its decimal fraction part.
    """

    def find_length_of_seq(n):
        """Returns the length of the recurring cycle for 1/[n]."""
        
        #We can find the length of the recurring digit cycle by finding the 
        #length of the first multiple of [n] which only has 9 in its digits.
        #This is because this number is the denominator of the fraction which
        #is equal to 1/[n], and for which the digit recurring cycle is the 
        #numerator.
        #
        #Example:
        #
        #n = 7 : 999999 % 7 == 0; 1/7 == 142857/999999;
        return first(
                     k for k in xrange(1, n + 1) if (10 ** k - 1) % n == 0
                    ) or 0
    
    #Return the result.
    return max_by(find_length_of_seq, (n for n in xrange(1, 1000)))

if __name__ == "__main__":
    cProfile.run("print(get_answer())")
